package rjl.dao.impl;

import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.Transaction;
import org.springframework.stereotype.Repository;
import rjl.dao.Userdao;
import rjl.domain.User;

import javax.annotation.Resource;
import java.util.List;

/**
 * Created by Administrator on 2017/2/28.
 */
@Repository
public class UserdaoImpl implements Userdao {
    @Resource
    private SessionFactory sessionFactory;
    protected Session getsession(){
        Session session =sessionFactory.getCurrentSession();
        return session;
    }
    /*private User[] user = new User[3];
        public void account(){
        user[0] = new User("rjl","123456");
        user[1] = new User("abc","000111");
        user[2] = new User("bcd","456789");
    }*/

    @Override
    public User findbyusernamepassword(String username, String password) {
       /* this.account();
        for (User user2:user){
            System.out.println(username);
            System.out.println(password);
            if (user2.getUsername().equals(username)){
                return null;
            }else{
                return user2;
            }
        }*/

//        Transaction transaction = session.beginTransaction();
        User user = (User) getsession().createQuery("From User u where u.username=? ")
                .setParameter(0,username)
                .uniqueResult();
        if (user != null){
//            transaction.commit();
//            session.close();
            System.out.println(username);
            return null;
        }else {
            user = new User();
            user.setUsername(username);
            user.setPassword(password);
            System.out.println(password);
            getsession().save(user);
           /* transaction.commit();
            session.close();*/
            return user;
        }
    }

    @Override
    public List<User> findAll() {
        return getsession().createQuery("from User").list();
    }
}
